package models

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"log"
	"newGame/utils"
	"os"
	"strings"
	"time"
)

type API uint

//获取验证码接口
func (api *API) APFC0001(c *gin.Context) {
	var (
		captcha   string
		err       error
		timestamp string
		SessionId string
	)
	timestamp = fmt.Sprintf("%d", time.Now().UnixNano())
	defer func() {
		_ = os.Remove(fmt.Sprintf("./media/images/%s.jpg", timestamp))
	}()
	SessionId, _ = c.Cookie("SessionId")
	if captcha, err = utils.GenerateCaptcha(timestamp); err != nil {
		log.Fatal(err)
		c.HTML(500, "500", nil)
		return
	}
	log.Println("验证码是", captcha)
	Db.RedisDb.HSet("captchaCache", SessionId, strings.ToLower(captcha))
	Db.RedisDb.Expire("captchaCache", 60*time.Second)
	c.File(fmt.Sprintf("./media/images/%s.jpg", timestamp))
}
//注册接口
func (api *API) APFC0002(c *gin.Context) {
	var (
		postData map[string]interface{}
		ctx      context.Context
		cancel   context.CancelFunc
		result   bson.M
		err      error
	)
	postData = make(map[string]interface{})
	_ = c.ShouldBindWith(&postData, binding.JSON)
	if !utils.CheckCaptcha(Db.RedisDb, c, postData["captcha"].(string)) {
		return
	}
	ctx, cancel = context.WithCancel(context.Background())
	defer cancel()
	if err = Db.MongoDb.Database("games").Collection("accounts").FindOne(ctx, bson.M{
		"username": postData["username"],
	}).Decode(&result); err != nil {
		if err == mongo.ErrNoDocuments {
			if _, err = Db.MongoDb.Database("games").Collection("accounts").InsertOne(ctx, bson.M{
				"username": postData["username"],
				"password": utils.GetMd5String(postData["username"]),
			}); err != nil {
				log.Println(err)
				c.JSON(500, gin.H{
					"pass": false,
					"msg":  "创建用户失败",
				})
				return
			} else {
				c.JSON(200, gin.H{
					"pass": true,
					"msg":  "创建用户成功",
				})
				return
			}
		} else {
			log.Println(err)
			c.JSON(500, gin.H{
				"pass": false,
				"msg":  "服务器错误",
			})
			return
		}
	}
	c.JSON(200, gin.H{
		"pass": false,
		"msg":  "账号已存在",
	})
}
//登陆接口
func (api *API) APFC0003(c *gin.Context) {
	var (
		postData map[string]interface{}
		ctx      context.Context
		cancel   context.CancelFunc
		result   bson.M
		err      error
		token    string
		claim    utils.Claims
	)
	postData = make(map[string]interface{})
	_ = c.ShouldBindWith(&postData, binding.JSON)
	if !utils.CheckCaptcha(Db.RedisDb, c, postData["captcha"].(string)) {
		return
	}
	ctx, cancel = context.WithCancel(context.Background())
	defer cancel()
	if err = Db.MongoDb.Database("games").Collection("accounts").FindOne(ctx, bson.M{
		"username": postData["username"],
	}).Decode(&result); err != nil {
		if err == mongo.ErrNoDocuments {
			c.JSON(200, gin.H{
				"pass": false,
				"msg":  "账号不存在",
			})
			return
		} else {
			log.Println(err)
			c.JSON(500, gin.H{
				"pass": false,
				"msg":  "服务器错误",
			})
			return
		}
	}
	if utils.GetMd5String(postData["password"]) == result["password"] {
		claim.Username = "admin"
		claim.Password = "admin"
		if token, err = utils.GenerateToken(&claim); err != nil {
			log.Println("token生成失败", err)
			c.JSON(500, gin.H{
				"pass": false,
				"msg":  "服务器错误",
			})
			return
		} else {
			c.SetCookie("token", token, 1800, "/", "127.0.0.1", false, false)
		}
		c.JSON(200, gin.H{
			"pass": true,
			"msg":  "登录成功",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"pass": false,
			"msg":  "密码错误",
		})
		return
	}
}
